// packageA/pages/refound/apply_return.js
function a(a, t, i) {
  a.animation = wx.createAnimation({
    transformOrigin: "50% 50%",
    duration: 400,
    timingFunction: "ease",
    delay: 0
  }), a.animation.translateY(t + "vh").step(), a.setData({
    animation: a.animation.export(),
    show: i
  });
}

function t(a) {
  var t;
  var that = this;
  p = [];
  for (var i = 0, e = 0; e < _.length; e++)
    0 == (t = _[e]).city_id && 0 == t.county_id && (p[i] = t,
      i++);
  a.setData({
    provinces: p
  });
}

function i(a, t) {
  var i;
  w = [];
  for (var e = 0, d = 0; d < _.length; d++) 0 == (i = _[d]).county_id && i.province_id == p[a].province_id && 0 != i.city_id && (w[e] = i,
    e++);
  0 == w.length && (w[0] = {
    name: ""
  }), t.setData({
    citys: w
  });
}

function e(a, t, i) {
  var e;
  f = [];
  for (var d = 0, n = 0; n < _.length; n++) 0 != (e = _[n]).county_id && e.province_id == p[a].province_id && e.city_id == w[t].city_id && (f[d] = e,
    d++);
  0 == f.length && (f[0] = {
    name: ""
  }), i.setData({
    countys: f
  });
}
var d, n, o, s, r, c, u, v, h, l, g, y = getApp(),
  _ = [],
  p = [],
  w = [],
  f = [],
  m = [0, 0, 0],
  D = 0,
  x = !1,
  S = 200;
_ = [],
  p = [],
  w = [],
  f = [],
  m = [0, 0, 0],
  D = 0,
  x = !1,
  S = 200;
let ss = {
  id: "",
  num: 1,
  pro: [],
  prostr: []
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShow: false,
    goods_cause: [], //服务类型
    // 省市区
    hidden: !1,
    show: x,
    province: p,
    city: w,
    county: f,
    province_id: p,
    city_id: w,
    county_id: f,
    value: [0, 0, 0],
    current: 1,
    index: 0,
    hasVoucher: 0, //是否有凭证
    tempFilePaths: [], //图片
    _tempFilePaths: [], //图片预览
    num: 1,
    rec_id: [],
    user_id: [],
    return_rec_id: [],
    refound_token: [],
    return_g_id: [],
    return_g_number: [],
    consignee: [],
    retrun_type: [],
    address_id: [],
    region_id: [],
    cause_id: [],
    parent_id: [],
    return_img: []
  },

  // 右侧导航
  toggle: function () {
    let that = this;
    that.setData({
      isShow: !that.data.isShow
    })
  },

  // 服务类型切换
  bindHeaderTap: function (e) {
    let that = this;
    let goods_cause = that.data.goods_cause;
    let index = e.currentTarget.dataset.index;
    let rec_id = e.currentTarget.dataset.recid;
    let d = that.data.d;
    let goods_id = that.data.goods_id;
    console.log('d', d)
    console.log('goods_id', goods_id)
    // 切换样式
    for (let i = 0; i < goods_cause.length; i++) {
      goods_cause[i].is_checked = 0;
    }
    goods_cause[index].is_checked = 1;

    // console.log(index);
    // console.log(goods_cause[index].lang);
    r = wx.getStorageSync("token");
    if (goods_cause[index].lang == "换货") {
      wx.request({
        url: y.apiUrl("refound/getspec"),
        data: {
          rec_id: rec_id,
        },
        method: "POST",
        header: {
          "Content-Type": "application/json",
          "X-ECTouch-Authorization": r
        },
        success: function (res) {
          console.log('getspec', res.data)
          that.setData({
            properties: res.data.spec,
            parent_cause: res.data.parent_cause,
            index: 0,
            retrun_type: 2
          })
        }
      })
    } else if (goods_cause[index].lang == "退款") {
      that.setData({
        goods_cause: goods_cause,
        retrun_type: 3
      })
    } else {
      that.setData({
        retrun_type: 1
      })
      that.apply_return(d, goods_id, rec_id, 1);
    }
    that.setData({
      goods_cause: goods_cause,
      cause_name: goods_cause[index].lang,
      input_value: '',
      //清空input
      addressee: '',
      leave_message: '',
      return_dis: ''
      // tempFilePaths:[]
    })

  },

  // 退货
  apply_return: function (order_id, goods_id, rec_id, retrun_type) {
    let that = this;
    r = wx.getStorageSync("token");
    wx.request({
      url: y.apiUrl("refound/applyreturn"),
      data: {
        order_id: order_id,
        goods_id: goods_id,
        rec_id: rec_id,
        retrun_type: 1
      },
      method: "POST",
      header: {
        "Content-Type": "application/json",
        "X-ECTouch-Authorization": r
      },
      success: function (res) {
        console.log('apply_return', res.data)
        console.log(res.data.address_id)
        that.addressData(res.data.address_id);
        if (res.data.cause_name == '退货') {
          that.setData({
            retrun_type: 1
          })
        } else if (res.data.cause_name == '换货') {
          that.setData({
            retrun_type: 2
          })
        } else if (res.data.cause_name == '退款') {
          that.setData({
            retrun_type: 3
          })
        }

        that.setData({
          goods: res.data.goods,
          goods_cause: res.data.goods_cause,
          parent_cause: res.data.parent_cause,
          cause_name: res.data.cause_name,
          userinfo: res.data.userinfo,
          num: res.data.goods.goods_number,
          user_id: res.data.user_id,
          index: 0,
          return_rec_id: res.data.return_rec_id,
          refound_token: res.data.refound_token,
          return_g_id: res.data.return_g_id,
          return_g_number: res.data.return_g_number,
          cause_id: res.data.parent_cause[0].cause_id,
          parent_id: res.data.parent_cause[0].parent_id
        })
        if (res.data.return_img) {
          let _tempFilePaths = [];
          for (let i = 0; i < res.data.return_img.length; i++) {
            _tempFilePaths.push(res.data.return_img[i].pic)
          }
          that.setData({
            tempFilePaths: res.data.return_img,
            _tempFilePaths: _tempFilePaths
          })
        }
      }
    });
  },
  // 省市区三联动
  addressData: function (d) {
    var a = this,
      r = wx.getStorageSync("token");
    wx.request({
      url: y.apiUrl("user/address/detail"),
      data: {
        id: d
      },
      method: "POST",
      header: {
        "Content-Type": "application/json",
        "X-ECTouch-Authorization": r
      },
      success: function (d) {
        if (t(a), void 0 != d.data.data) {
          var r = d.data.data.address.province_id,
            c = d.data.data.address.city_id,
            u = d.data.data.address.district_id;
          n = 0, o = 0, s = 0;
          for (var v = 0; v < a.data.provinces.length; v++) a.data.provinces[v].province_id == r && (n = v);
          i(n, a);
          for (var h = 0; h < a.data.citys.length; h++) a.data.citys[h].region_id == c && (o = h);
          e(n, o, a);
          for (var l = 0; l < a.data.countys.length; l++) a.data.countys[l].region_id == u && (s = l);
          a.setData({
            value: [n, o, s]
          }), a.setData({
            addressDeatil: d.data.data,
            consignee: d.data.data.consignee,
            mobile: d.data.data.mobile,
            address: d.data.data.address,
            province: d.data.data.address.province,
            city: d.data.data.address.city,
            county: d.data.data.address.district,
            province_id: d.data.data.address.province_id,
            city_id: d.data.data.address.city_id,
            county_id: d.data.data.address.district_id,
            hidden: !0,
            address_id: d.data.data.address.id,
            region_id: d.data.data.city[0].parent_id
          });
        }
      }
    });
  },
  bindChange: function (a) {
    let t = a.detail.value;
    m[0] != t[0] ? (t[1] = 0, t[2] = 0, i(t[0], this), e(t[0], t[1], this)) : m[1] != t[1] && (t[2] = 0,
        e(t[0], t[1], this)), m = t, r = [t[0], t[1], t[2]], c = p[t[0]].region_name,
      u = w[t[1]].region_name, v = f[t[2]].region_name, h = p[t[0]].region_id, l = w[t[1]].region_id,
      g = f[t[2]].region_id, this.setData({
        value: [t[0], t[1], t[2]]
      });
  },
  checkFloatView: function (t) {
    let i = this;
    D = 0, a(this, S = 200, x = !0), this.setData({
      value: r,
      province: void 0 == c ? "" : c,
      city: void 0 == u ? "" : u,
      county: void 0 == v ? "" : v,
      province_id: void 0 == h ? "0" : h,
      city_id: void 0 == l ? "0" : l,
      county_id: void 0 == g ? "0" : g,
      showViewMol: !i.data.showViewMol
    });
  },
  hiddenFloatView: function (t) {
    let i = this;
    D = 0, a(this, S = 200, x = !0), i.setData({
      showViewMol: !i.data.showViewMol
    });
  },
  translate: function (t) {
    let i = this;
    console.log(i.data)
    0 == D ? (S = 0, x = !1, D = 1) : (S = 200, x = !0, D = 0), a(this, S, x), r = [0, 0, 0],
      c = "北京", u = "北京", v = "东城区", h = "2", l = "52", g = "500", i.setData({
        showViewMol: !i.data.showViewMol
      });
  },

  // 提交申请
  upload_info: function (e) {
    let that = this;
    let return_rec_id = that.data.return_rec_id;
    let refound_token = that.data.refound_token;
    let return_g_id = that.data.return_g_id;
    let return_g_number = that.data.return_g_number;
    let value = that.data.value;
    let province = that.data.province;
    let city = that.data.city;
    let county = that.data.county;
    let province_id = that.data.province_id;
    let city_id = that.data.city_id;
    let county_id = that.data.county_id;
    let voucher = that.data.hasVoucher; //申请凭证：是/否
    let properties = that.data.properties; //换货商品属性
    let retrun_type = that.data.retrun_type; //服务类型
    let address_id = that.data.address_id;
    let region_id = that.data.region_id;
    let _tempFilePaths = that.data._tempFilePaths;
    let tempFilePaths = that.data.tempFilePaths;
    let cause_id = that.data.cause_id;
    let parent_id = that.data.parent_id;

    let attr_val = [];
    for (const key in properties) {
      for (let i = 0; i < properties[key].values.length; i++) {
        if (properties[key].values[i].checked) {
          attr_val.push(properties[key].values[i].id)
        }
      }
    }

    let consignee = e.detail.value.consignee == undefined ? '' : e.detail.value.consignee;
    let mobile = e.detail.value.mobile == undefined ? '' : e.detail.value.mobile;
    let email = e.detail.value.email == undefined ? '' : e.detail.value.email;
    let addressee = e.detail.value.addressee == undefined ? '' : e.detail.value.addressee;
    let return_dis = e.detail.value.return_dis == undefined ? '' : e.detail.value.return_dis;
    let number = e.detail.value.number == undefined ? '' : e.detail.value.number;
    let leave_message = e.detail.value.leave_message == undefined ? '' : e.detail.value.leave_message;

    let cause_name = that.data.cause_name;
    let mobile_reg = /^1(3[0-9]|4[5,7]|5[0,1,2,3,5,6,7,8,9]|6[2,5,6,7]|7[0,1,7,8]|8[0-9]|9[1,8,9])\d{8}$/;
    let email_reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;

    if (typeof return_dis === "undefined" || return_dis == null || return_dis.trim() == "") {
      wx.showToast({
        title: '问题描述有误，请重新填写',
        icon: 'none'
      })
      return false;
    }

    if (cause_name == '退货') {
      that.setData({
        retrun_type: 1
      })
    } else if (cause_name == '退款') {
      that.setData({
        retrun_type: 3
      })
    } else if (cause_name == '换货') {
      that.setData({
        retrun_type: 2
      })
      if (typeof consignee === "undefined" || consignee == null || consignee.trim() == "") {
        wx.showToast({
          title: '联系人姓名有误，请重新填写',
          icon: 'none'
        })
        return false;
      }
      if (!mobile_reg.test(mobile)) {
        wx.showToast({
          title: '手机号码有误，请重新填写',
          icon: 'none'
        })
        return false;
      }
      if (typeof addressee === "undefined" || addressee == null || addressee.trim() == "") {
        wx.showToast({
          title: '详细地址有误，请重新填写',
          icon: 'none'
        })
        return false;
      }
    }
    if (email != '') {
      if (!email_reg.test(email)) {
        wx.showToast({
          title: '邮箱有误，请重新填写',
          icon: 'none'
        })
        return false;
      }
    }
    if (tempFilePaths.length <= 0) {
      wx.showToast({
        title: '请上传图片信息',
        icon: 'none'
      })
      return false;
    }



    r = wx.getStorageSync("token");
    wx.request({
      url: y.apiUrl('refound/submitreturn'),
      method: 'POST',
      data: {
        return_rec_id: return_rec_id,
        return_g_id: return_g_id,
        return_g_number: return_g_number,
        return_type: retrun_type,
        attr_val: attr_val,
        goods_number: number,
        credentials: 0,
        img: _tempFilePaths,
        textfield: 'txt',
        addressee: addressee,
        mobile: mobile,
        email: email,
        province_region_id: province_id,
        city_region_id: city_id,
        district_region_id: county_id,
        street: '',
        village_region_id: '',
        region_id: region_id,
        address_id: address_id,
        refound_token: refound_token,
        credentials: voucher,
        cause_id: cause_id,
        parent_id: parent_id,
        chargeoff_status: 0,
        return_brief: return_dis,
        return_remark: leave_message,
        addressee: consignee
      },
      header: {
        "Content-Type": "application/json",
        "X-ECTouch-Authorization": r
      },
      success(res) {
        console.log('提交成功', res.data)
        wx.redirectTo({
          url: './detail?ret_id=' + res.data.ret_id,
        })
      }
    })
  },

  // 属性选择
  modelTap: function (event) {
    let that = this;
    let id = event.currentTarget.dataset.id;
    let specName = event.currentTarget.dataset.name;
    let _properties = that.data.properties;
    for (const key in _properties) {
      if (_properties[key].name == specName) {
        for (let i = 0; i < _properties[key].values.length; i++) {
          if (_properties[key].values[i].id == id) {
            //如果已经选中，则反选
            if (_properties[key].values[i].checked) {
              _properties[key].values[i].checked = 0;
            } else {
              _properties[key].values[i].checked = 1;
            }
          } else {
            _properties[key].values[i].checked = 0;
          }
        }
      }
    }
    that.setData({
      properties: _properties
    })
  },

  //数量
  up: function (e) {
    let t = this.data.num;
    let maxNum = e.target.dataset.maxNum;
    if (t >= maxNum) {
      wx.showToast({
        title: '不能超过最大数量',
        icon: 'none'
      })
    } else {
      t++;
      this.setData({
        num: t
      });
      ss.num = t;
    }
    // this.getGoodsTotal();
  },
  down: function () {
    let t = this.data.num;
    --t <= 1 && (t = 1), this.setData({
      num: t
    });
    ss.num = t;
    //  this.getGoodsTotal();
  },
  import: function (t) {
    let o = Math.floor(t.detail.value);
    o <= 1 && (o = 1), o >= 999 && (o = 999), this.setData({
      num: o
    });
    ss.num = o;
    // this.getGoodsTotal();
  },

  //图片上传
  ChooseImg: function () {
    let that = this;
    wx.chooseImage({
      count: 6, // 默认最多9张图片，可自行更改
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: y.apiUrl('refound/imgreturn'), //上传图片接口地址
            filePath: res.tempFilePaths[i],
            name: 'images',
            formData: {
              rec_id: that.data.rec_id,
              user_id: that.data.user_id
            },
            success: function (res) {
              if (JSON.parse(res.data).error == 1) {
                wx.showToast({
                  title: '最多只能选择6张照片',
                  icon: 'none',
                  duration: 2000,
                  mask: true
                })
              } else {
                wx.showToast({
                  title: '正在上传...',
                  icon: 'loading',
                  mask: true,
                  duration: 1000
                });
                let _tempFilePaths = [];
                for (let i = 0; i < JSON.parse(res.data).length; i++) {
                  _tempFilePaths.push(JSON.parse(res.data)[i].pic)
                }
                that.setData({
                  tempFilePaths: JSON.parse(res.data),
                  _tempFilePaths: _tempFilePaths
                })
              }
            },
            fail: function (error) {
              console.log(error);
            }
          })
        }
      }
    })
  },

  //预览图片
  PreviewImg: function (e) {
    let index = e.target.dataset.index;
    let that = this;
    //console.log(that.data.tempFilePaths[index]);
    //console.log(that.data.tempFilePaths);
    wx.previewImage({
      current: that.data.tempFilePaths[index],
      urls: that.data._tempFilePaths,
    })
  },

  //删除图片
  DeleteImg: function (e) {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          //console.log('点击确定了');
          let r = wx.getStorageSync("token");
          wx.request({
            url: y.apiUrl("refound/clearpictures"),
            data: {
              id: e.currentTarget.dataset.id,
              rec_id: that.data.rec_id
            },
            method: "POST",
            header: {
              "Content-Type": "application/json",
              "X-ECTouch-Authorization": r
            },
            success: function (res) {
              let _tempFilePaths = [];
              for (let i = 0; i < res.data.length; i++) {
                _tempFilePaths.push(res.data[i].pic)
              }
              that.setData({
                tempFilePaths: res.data,
                _tempFilePaths: _tempFilePaths
              })
            }
          });
        } else if (res.cancel) {
          //console.log('点击取消了');
          return false;
        }
      }
    })
  },
  // 申请凭证
  voucherCheckbox: function (e) {
    let that = this;
    let hasVoucher = this.data.hasVoucher;
    if (hasVoucher == 0) {
      that.setData({
        hasVoucher: 1
      })
    } else if (hasVoucher == 1) {
      that.setData({
        hasVoucher: 0
      })
    }
  },
  bindPickerChange: function (e) {
    let that = this;
    console.log('picker发送选择改变，携带值为', e.detail.value)
    let parent_cause = that.data.parent_cause;
    console.log('parent_cause', parent_cause);
    let cause_id = parent_cause[e.detail.value].cause_id;
    let parent_id = parent_cause[e.detail.value].parent_id;
    console.log('parent_id', parent_id)
    that.setData({
      index: e.detail.value,
      cause_id: cause_id,
      parent_id: parent_id
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    let that = this;
    d = options.order_id;
    let goods_id = options.goods_id;
    let rec_id = options.rec_id;
    that.setData({
      d: d,
      goods_id: goods_id,
      rec_id: rec_id
    })
    _ = wx.getStorageSync("region");
    that.apply_return(d, goods_id, rec_id, 1);
    that.animation = wx.createAnimation({
        transformOrigin: "50% 50%",
        duration: 0,
        timingFunction: "ease",
        delay: 0
      }),
      that.animation.translateY("200vh").step(),
      that.setData({
        animation: that.animation.export(),
        show: x
      });


    let phone = wx.getSystemInfoSync(); //调用方法获取机型
    if (phone.platform == 'ios') {
      that.setData({
        isIos: true
      });
    } else if (phone.platform == 'android') {
      that.setData({
        isIos: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})